﻿using System;
using System.IO;
using Hongsh.Pay.Client.Proxy.Http;
using MapleLeaf.Pay;
using MapleLeaf.Pay.Pay;
using MapleLeaf.Pay.Trade;

namespace Hongsh.Pay.Client.Proxy.Handlers {
    // Token: 0x0200007A RID: 122
    public static class TonesPayProxy {
        // Token: 0x0600044F RID: 1103 RVA: 0x000049E2 File Offset: 0x00002BE2
        public static void AddTonesPayProxyHandler(this HttpServer svr) {
            svr.RouterList.Add("POST/", new HttpContextActionDelegate(Process));
        }

        // Token: 0x06000450 RID: 1104 RVA: 0x0000FDB8 File Offset: 0x0000DFB8
        private static void Process(HttpContext ctx) {
            string src = new StreamReader(ctx.Request).ReadToEnd();
            TonesPayReq tonesPayReq = src.smethod_2().ToObject<TonesPayReq>();
            if (!tonesPayReq.TransType.Equals("SALE", StringComparison.OrdinalIgnoreCase)) {
                ctx.Result = HttpResult.NoFound;
            }
            else {
                TonesPayResp tonesPayResp = new TonesPayResp {
                    MID = tonesPayReq.MID,
                    TID = tonesPayReq.TID,
                    Amount = tonesPayReq.Amount,
                    CardNo = tonesPayReq.CardNo,
                    TraceNo = tonesPayReq.TraceNo,
                    inVoiceNo = tonesPayReq.inVoiceNo,
                    TransType = tonesPayReq.TransType,
                    TransDate = tonesPayReq.TransDate,
                    TransTime = tonesPayReq.TransTime,
                    RespCode = "00"
                };
                try {
                    HongshPayTrade hongshPayTrade = ctx.Execute(new TradeAuthPaymentRequest {
                        Amount = tonesPayReq.Amount,
                        Authcode = tonesPayReq.CardNo
                    });
                    DateTime t = DateTime.Now.AddSeconds(40.0);
                    tonesPayResp.TransID = hongshPayTrade.TradeId;
                    while (hongshPayTrade.State == TradeState.未知 && DateTime.Now <= t) {
                        hongshPayTrade = ctx.Execute(new TradePaymentQueryRequest {
                            TradeId = tonesPayResp.TransID
                        });
                    }
                    if (hongshPayTrade.State != TradeState.成功) {
                        throw new Exception(string.IsNullOrEmpty(hongshPayTrade.StateDescript) ? hongshPayTrade.StateDescript : "交易失败或超时，请撤销交易！");
                    }
                    tonesPayResp.PayID = hongshPayTrade.Payer;
                }
                catch (Exception ex) {
                    tonesPayResp.RespCode = "05";
                    tonesPayResp.RespMessage = ex.Message;
                }
                ctx.Result = new HttpXmlResult(tonesPayResp, "TxnResp");
            }
        }
    }
}
